import dayjs from 'dayjs';
import {
  couponsData
} from './mock';
import {
  ds
} from '~/tools/data';
import {
  ui
} from '~/tools/ui';
import {
  resource
} from '~/static/resource'

const emptyCouponImg = resource.img.coupon;

Component({
  properties: {
    storeId: String,
    canSelect: {
      type: Boolean,
      value: true
    },
    goodsIds: {
      type: Array,
      value: []
    },
    settleDetailData: {
      type: Object,
      value: {}
    },
    promotionGoodsList: {
      type: Array,
      value: [],
    },
    orderSureCouponList: {
      type: Array,
      value: [],
    },
    couponsShow: {
      type: Boolean,
      value: false,
      observer(couponsShow) {
        if (couponsShow) {
          const {
            promotionGoodsList,
            orderSureCouponList,
            storeId,
            goodsIds,
            settleDetailData
          } = this.data;
          // console.log(settleDetailData, goodsIds)
          const products =
            promotionGoodsList &&
            promotionGoodsList.map((goods) => {
              this.storeId = goods.storeId;
              return {
                skuId: goods.skuId,
                spuId: goods.spuId,
                storeId: goods.storeId,
                selected: true,
                quantity: goods.num,
                prices: {
                  sale: goods.settlePrice,
                },
              };
            });
          const selectedCoupons =
            orderSureCouponList &&
            orderSureCouponList.map((ele) => {
              return {
                promotionId: ele.promotionId,
                storeId: ele.storeId,
                couponId: ele.couponId,
              };
            });
          this.setData({
            products,
          });
          // 加载优惠券
          this.coupons({
            products,
            selectedCoupons,
            storeId,
          }).then((res) => {
            this.initData(res)
            ui.loading(false)
            this.setData({
              loaded: true
            })
          });
        }
      },
    },
  },
  data: {
    emptyCouponImg,
    goodsList: [],
    selectedList: [],
    couponsList: [],
    orderSureCouponList: [],
    promotionGoodsList: [],
    loaded: false
  },
  methods: {
    initData(data = {}) {
      const {
        couponResultList = [], reduce = 0
      } = data;
      const selectedList = [];
      let selectedNum = 0;
      const couponsList =
        couponResultList &&
        couponResultList.map((coupon) => {
          const {
            status,
            couponVO,
            source
          } = coupon;
          const {
            couponId,
            condition = '',
            endTime = 0,
            name = '',
            startTime = 0,
            value,
            type,
            scopeText
          } = couponVO;
          if (status === 1) {
            selectedNum++;
            selectedList.push({
              couponId,
              promotionId: ruleId,
              storeId: this.storeId,
            });
          }
          const val = (type === 2 ? value / 100 : value);
          const timeLimit = () => {
            if (+startTime > 0 && +endTime > 0) return `${dayjs(+startTime).format('YYYY-MM-DD')} ~ ${dayjs(
              +endTime,).format('YYYY-MM-DD')}`
            return '永久有效'
          }
          return {
            key: couponId,
            title: name,
            isSelected: false,
            timeLimit: timeLimit(),
            value: val,
            status: status === -1 ? 'useless' : 'default',
            desc: condition,
            type,
            tag: '',
            source,
            scopeText
          };
        });
      this.setData({
        selectedList,
        couponsList,
        reduce,
        selectedNum,
      });
    },
    selectCoupon(e) {
      const {
        key
      } = e.currentTarget.dataset;
      const {
        couponsList,
        selectedList
      } = this.data;
      couponsList.forEach((coupon) => {
        if (coupon.key === key) {
          coupon.isSelected = !coupon.isSelected;
        }
      });

      const couponSelected = couponsList.filter(
        (coupon) => coupon.isSelected === true,
      );

      this.setData({
        selectedList: [...selectedList, ...couponSelected],
        couponsList: [...couponsList],
      });

      this.triggerEvent('sure', {
        selectedList: [...selectedList, ...couponSelected],
      });
    },
    hide() {
      this.setData({
        couponsShow: false,
        loaded: false
      });
    },
    async coupons() {
      ui.loading()
      await this.loadUser()
      await this.loadGoods()

      const couponRes = await ds.coll('coupons')
        .get()
      const couponList = couponRes.data

      return new Promise(resolve => {
        const resultList = couponList.map(ele => {
          const coupon = {
            couponVO: {
              condition: `满${ele.unit}元可用`,
              couponId: ele._id,
              startTime: ele.start,
              endTime: ele.end,
              name: ele.title || '满减券',
              profit: `￥${ele.minus}`,
              promotionCode: 90,
              promotionSubCode: 1,
              scopeText: this.getScopeText(ele),
              storeId: this.data.storeId,
              value: Number(ele.minus),
              type: 1,
            },
            status: 0, // 0:未勾选。1:勾选。-1:置灰
            source: ele
          }

          return this.validateCoupon(coupon)
        })
        // console.log('coupon list', resultList)
        resolve({
          couponResultList: this.sortCoupons(resultList.filter(ele => ele != null)),
          reduce: 1000,
        })
      })
    },
    sortCoupons(coupons) {
      const result = (coupons || []).sort((a, b) => {
        if (a.status != b.status) return -(a.status - b.status)
        if (a.couponVO.value != b.couponVO.value) return -(a.couponVO.value - b.couponVO.value)
        return a.couponVO.unit - b.couponVO.unit
      })
      // console.log('sort coupons', result)
      return result
    },
    getScopeText(source) {
      const {
        user
      } = this.data
      let text = ''
      const append = txt => (text = (text ? text + ', ' + txt : txt))
      if (source.userId) append('限定用户')
      if (source.onlyVip) append('VIP可用')
      if (source.goodsId) append('限定商品')
      if (source.openGId) append('群专属')
      if (source.limit) append(`限${source.limit}张（已用${user.couponRecord?.[source._id]?.num||0}）`)
      if (source.num) append(`剩余${source.openGId?source.left:source.num}`)
      // console.log('scope text', source, text)
      return text || '无限定'
    },
    validateCoupon(coupon) {
      const {
        user,
        goodsList,
        goodsIds,
        settleDetailData
      } = this.data
      const {
        source
      } = coupon
      // 判断可用条件
      if (source.onlyVip) {
        if (!user.vip) {
          coupon.couponVO.scopeText = '仅VIP可用'
          coupon.status = -1
          return coupon
        }
      }
      if (source.start && source.end) {
        const curTime = new Date().getTime()
        if (curTime < source.start || curTime > source.end) {
          coupon.couponVO.scopeText = '不在有效期内'
          coupon.status = -1
          return coupon
        }
      }
      if (source.openGId) {
        if (source.openGId != user.couponRecord?.[source._id]?.openGId) {
          coupon.couponVO.scopeText = '尚未从群领取，咨询老板进群领券~'
          coupon.status = -1
          return coupon
        }
      }
      if (source.num && !(Number(source.num) > 0)) {
        coupon.couponVO.scopeText = '已抢光'
        coupon.status = -1
        return coupon
      }
      if (source.goodsId) {
        if (goodsIds.indexOf(source.goodsId) < 0) {
          coupon.couponVO.scopeText = '当前商品不可用'
          coupon.status = -1
          return null
        }
        // 查看当前商品金额是否满足额度要求
        const skuDetailVos = settleDetailData.storeGoodsList[0].skuDetailVos
        // console.log(skuDetailVos)
        const {
          payPrice,
          quantity
        } = skuDetailVos.filter(ele => (ele.skuId ?? ele.spuId) == source.goodsId)[0] || {}
        // console.log(payPrice * 1 * quantity, source.unit * 1)
        if (!payPrice || !quantity || !(payPrice * 1 * quantity >= source.unit * 1)) {
          coupon.couponVO.scopeText = '指定商品未满消费额'
          coupon.status = -1
          return coupon
        }
      } else { // 查看总商品金额是否满足
        const {
          totalPayAmount,
          totalDeliveryFee
        } = settleDetailData || {}
        // console.log((totalPayAmount * 1 - totalDeliveryFee * 1), source.unit * 1)
        if (!(totalPayAmount * 1 - totalDeliveryFee * 1 >= source.unit * 1)) {
          coupon.couponVO.scopeText = '未满消费额'
          coupon.status = -1
          return coupon
        }
      }
      if (source.userId && source.userId != user._id) {
        coupon.couponVO.scopeText = '当前用户不可用'
        coupon.status = -1
        return null
      }
      if (source.limit) {
        const {
          num
        } = user.couponRecord?.[source._id] || {}
        if ((num || 0) * 1 >= source.limit * 1) {
          coupon.couponVO.scopeText = '已达到限领量'
          coupon.status = -1
          return coupon
        }
      }
      return coupon
    },
    coupons_(coupon = {}) {
      return new Promise((resolve, reject) => {
        if (coupon?.selectedCoupons) {
          resolve({
            couponResultList: couponsData.couponResultList,
            reduce: couponsData.reduce,
          });
        }
        return reject({
          couponResultList: [],
          reduce: undefined,
        });
      });
    },
    async loadUser() {
      const user = await new Promise(resolve => {
        ds.cloudGetByOpenid('users', res => {
          const user = res.result.data[0]
          resolve(user)
        })
      })
      this.setData({
        user
      })
      // console.log('user', user)
    },
    async loadGoods() {
      const _ = ds.cmd
      const goodsIds = this.data.goodsIds
      const goodsRes = await ds.coll('goods')
        .where({
          _id: _.in(goodsIds)
        })
        .get()
      const goodsList = goodsRes.data
      this.setData({
        goodsList
      })
      // console.log('goods list', goodsList)
    },
  },
});